<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Bookdetail;
use app\admin\model\Tips;
use think\Db;
use think\Request;
use think\Cache;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use fast\Http;
use addons\third\library\Service;
use app\common\library\Auth;
use addons\third\model\Third;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['get_category,index,category_list,getBookDetail'];

    public function _initialize()
    {
        parent::_initialize();
        // $this->user_id = Cache::get('user_id');
        $this->model = new \app\admin\model\Bookdetail;
        $this->user_id = $this->auth->id;
    }  

    public function tips()
    {
        $tips = new Tips;
        $data = $this->request->request();
        $data['user_id'] = $this->user_id;
        
        $res = $tips->allowField(true)->save($data);
        if($res){
            $this->success('提交成功');
        }else{
            $this->error('提交失败');
        }


    }

    public function upload(){
        if(empty($_FILES)){
            return $this->view->fetch();
        }else{
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');

            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $this->success('上传成功','/uploads/'.$info->getSaveName());
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }
        
    }
    public function get_category()
    {
        $category_list = Db::name('category')->field('name,id')->select();
        $this->success('分类名称',$category_list);
    }

    /**
     * 预约操作
     * @ApiRoute (/api/index/order)
     * @ApiParams  buy_phone int 11 buy_phone:预约者手机或者qq号码
     * @ApiParams  id 书本管理
     * @ApiMethod   (POST)
     */
    public function order()
    {
        $bookdetail = new Bookdetail();
        $data = $this->request->request();
        // $data['buy_id'] = $this->auth->id;
        $data['buy_id'] = $this->user_id;
        if($data['buy_phone']==''){
            $this->error('请输入手机号码');
        }

        if(!empty($data['id'])){
            $id = $data['id'];
            $detail = $this->model->with(['fabuuser'])->where(['id'=>$id])->find();
            if($detail['status']==1){
                $this->error('该书本已经被人预约咯');
            }else{
                
                unset($data['id']);
                $data['status'] = 1;
                $r = $bookdetail->allowField(true)->save($data,['id'=>$id]);
                if($r){
                    $this->success('更新成功');
                }else{
                    $this->error('更新失败');
                }
            }
            
        }else{
            $this->error('缺少书本id参数');
        }


    }

    /**
     * 首页
     * icons 分类
     * book_list 最新上架
     */
    public function index()
    {

        $icons = Db::name('category')->field('id,name,image')->order('weigh')->select();
        $book_list = $this->model->field('id,name,image')->order('createtime desc')->select();
        $data = [
            'user_id'=>$this->user_id,
            'icons' => $icons,
            'book_list'=>$book_list,
        ];
        $this->success('请求成功',$data);
    }

    /**
    * 书本管理
    * @ApiTitle    (管理)
    * @ApiSummary  (管理)
    * @ApiMethod   (POST)
    * @ApiRoute    (/api/index/book_upload/action/:action)
    * @ApiHeaders  (name=token,type=string,required=true,description=)
    * @ApiParams   (name="action",type=string,required=true,description="url上传递,操作:add=添加/修改,find=,list=查看,delete=删除")
    * ids修改时候传过来 id=书本id
    * status 审核:0=未预约,1=已预约
    */
    public function book_upload($action)
    {
        $data = $this->request->request();
        // $data['user_id'] = $this->auth->id;
        $data['user_id'] = $this->user_id;

        // $this->success('test',$this->auth);
        $bookdetail = new Bookdetail();
        switch ($action) {
            case 'add':
                if(!empty($data['id'])){
                    $id = $data['id'];
                    unset($data['id']);
                }
                foreach($data as $key=>$val)
                {
                    if($key=='s')
                    {
                    unset($data[$key]);
                    }
                }
                
                $check = $bookdetail::where($data)->find();
                if($check){
                    $this->error('请勿重复添加',$check);
                }
                if(!empty($id)){
                    $r = $bookdetail->allowField(true)->save($data,['id'=>$id]);
                    if($r){
                        $this->success('更新成功',$r);
                    }else{
                        $this->error('更新失败');
                    }
                }else {
                    $validate = new Validate(
                        [
                            'category_id'  => 'require',
                            'name' => 'require',    
                            'fabu_phone' => 'require',
                        ],
                        [
                            'category_id.require'=>'分类必须',
                            'name.require'=>'书名必须',
                            'fabu_phone.require'=>'qq号码必须',
                        ]
                    );
                    if (!$validate->check($data)) {
                        $this->error($validate->getError(),$this->user_id);
                    }
                    $r = $bookdetail->allowField(true)->save($data);
                }
                
                if($r){
                    $this->success('添加成功',$this->user_id);
                }else{
                    $this->error('添加失败');
                }
                break;
            case 'list':
                $list = $bookdetail->where(['status'=>$data['status']])->where(['user_id'=>$this->user_id])->select();

                $this->success('获取列表成功',$list);
                break;
            case 'delete':
                $r = $bookdetail->where($data)->delete();
                if($r){
                    $this->success('删除成功');
                }else{
                    $this->error('你没有权限删除本书本,或书本不存在');
                }
                break;
            case 'find':
                $r = $bookdetail->where(['id'=>$data['id']])->find();
                $this->success('获取成功',$r);
                break;
            default:
                $this->error('action为必填项');
                break;
        }
    }

    /**
     * @ApiMethod   (POST)
     * 涉及到的功能：1、点击分类后获取到的书本列表2、首页的搜索
     * @param  int $id 分类id
     * @param  int $page 分页
     * @param  string $name 搜索商品名称
     * @return void
     */
    public function category_list(){
        $categoryid = $this->request->request('id');
        $page = $this->request->request('page');
        $rename = $this->request->request('name');

        // 筛选条件
        $filter = [];

        if(!empty($rename))
        $filter['name'] = ['like', '%' . trim($rename) . '%'];

        if(!empty($categoryid))
        $filter['category_id'] = $categoryid;

        // $filter['status'] = '0';//未预约

        $blistdatarList = Db::name('bookdetail')->field(['id,price,name,image,description'
        ])->where($filter)
            ->paginate(10, false, [ 'page' => $page ]);

        $this->success('获取分类书本列表', [
            'listdata'  => $blistdatarList,
        ]);
    }

    /**
    *
    * @ApiTitle    (获取书本详情)
    * @ApiMethod   (GET)
    * @ApiRoute    (/api/index/getBookDetail/id/:id)
    * @ApiParams   (name='id',type='int',required=true,description='书本id')
    */
    public function getBookDetail($id)
    {
        $bookdetail = Db::name('bookdetail')->where('id',$id)->find();

        $this->success('获取书本详情成功',$bookdetail);
    }


}
